package org.qianji.goosql.table;

import java.util.List;
import java.util.Map;

import org.qianji.goosql.dql.QueryStatement;

/**
 * 子查询表，用于表示由查询语句临时构造的表。
 * 
 * @author gmz
 * 
 */
public class SubQueryTable extends AbstractTable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4458384259327777012L;

	private QueryStatement subQuery;
	private String tempTableName;

	/**
	 * 由查询语句和临时表名构造子查询表。
	 * 
	 * @param subQuery
	 *            {@link QueryStatement QueryStatement} 子查询语句
	 * @param tempTableName
	 *            {@link java.lang.String String} 临时表名
	 */
	public SubQueryTable(QueryStatement subQuery, String tempTableName) {
		super();
		if (subQuery == null || tempTableName == null || tempTableName.isEmpty()) {
			throw new NullPointerException("args can't be null");
		}
		this.subQuery = subQuery;
		this.tempTableName = tempTableName;
	}

	/**
	 * 获取子查询语句
	 * 
	 * @return {@link QueryStatement QueryStatement} 子查询语句
	 */
	public QueryStatement getSubQuery() {
		return subQuery;
	}

	/**
	 * 获取临时表名
	 * 
	 * @return {@link java.lang.String String} 临时表名
	 */
	public String getTempTableName() {
		return tempTableName;
	}

	@Override
	public String getTable() {
		StringBuffer tab = new StringBuffer("(").append(subQuery.toSql()).append(")");
		return tab.toString();
	}

	@Override
	public String getTableName() {
		return tempTableName;
	}

	@Override
	public String toSql() {
		StringBuffer tab = new StringBuffer("(").append(subQuery.toSql()).append(") ").append(tempTableName);
		return tab.toString();
	}

	@Override
	public List<Object> getPlacedParameters() {
		return subQuery.getPlacedParameters();
	}

	@Override
	public Map<String, Object> getNamedParameters() {
		return subQuery.getNamedParameters();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null || !(obj instanceof SubQueryTable)) {
			return false;
		}
		SubQueryTable other = (SubQueryTable) obj;
		if (subQuery.equals(other.getSubQuery()) && tempTableName.equals(other.getTempTableName())) {
			return true;
		}
		return false;
	}

	@Override
	public int hashCode() {
		int hc = 17;
		hc = 37 * hc + subQuery.hashCode();
		hc = 37 * hc + tempTableName.hashCode();
		return hc;
	}

	@Override
	public String toString() {
		return toSql();
	}

}
